package alertPeople

import (
	"context"
	"devops-super/api"
	v1 "devops-super/api/alerts/v1"
	"devops-super/internal/dao"
	"devops-super/internal/model/entity"
	"devops-super/internal/model/mymodel"
	"devops-super/internal/service"
	"devops-super/utility/util/arrayUtil"
	"errors"
	"github.com/gogf/gf/v2/os/glog"
)

type sAlertPeople struct{}

var cols = dao.AlertPeople.Columns()

func init() {
	service.RegisterAlertPeople(New())
}

func New() *sAlertPeople {
	return &sAlertPeople{}
}

// Add 添加告警人员
func (*sAlertPeople) Add(ctx context.Context, in *entity.AlertPeople) (err error) {
	// 验证手机号是否已存在
	count, _ := dao.AlertPeople.Ctx(ctx).Where(cols.Phone, in.Phone).Count()
	if count > 0 {
		return errors.New("手机号已存在")
	}

	// 验证邮箱是否已存在
	count1, _ := dao.AlertPeople.Ctx(ctx).Where(cols.Email, in.Email).Count()
	if count1 > 0 {
		return errors.New("邮箱已存在")
	}

	_, err = dao.AlertPeople.Ctx(ctx).Insert(in)
	return
}

// Upt 更新告警人员
func (*sAlertPeople) Upt(ctx context.Context, in *entity.AlertPeople) (err error) {
	// 验证手机号是否已存在（排除当前记录）
	count, _ := dao.AlertPeople.Ctx(ctx).Where(cols.Phone, in.Phone).Where(cols.Id+" != ", in.Id).Count()
	if count > 0 {
		return errors.New("手机号已存在")
	}

	// 验证邮箱是否已存在（排除当前记录）
	count1, _ := dao.AlertPeople.Ctx(ctx).Where(cols.Email, in.Email).Where(cols.Id+" != ", in.Id).Count()
	if count1 > 0 {
		return errors.New("邮箱已存在")
	}

	_, err = dao.AlertPeople.Ctx(ctx).WherePri(in.Id).OmitNilData().Data(in).Update()
	return
}

// GetPageLst 分页获取告警人员列表
func (*sAlertPeople) GetPageLst(ctx context.Context, req *v1.AlertPeopleGetPageLstReq) (out *api.PageLstRes[*mymodel.AlertPeopleResponse], err error) {
	out = &api.PageLstRes[*mymodel.AlertPeopleResponse]{}
	m := dao.AlertPeople.Ctx(ctx).Safe(true)

	// 姓名模糊查询
	if req.Name != "" {
		m = m.Where(cols.Name+" like ? ", "%"+req.Name+"%")
	}

	// 部门筛选
	if req.DeptId != 0 {
		m = m.Where(cols.DeptId, req.DeptId)
	}

	// 手机号模糊查询
	if req.Phone != "" {
		m = m.Where(cols.Phone+" like ? ", "%"+req.Phone+"%")
	}

	// 邮箱模糊查询
	if req.Email != "" {
		m = m.Where(cols.Email+" like ? ", "%"+req.Email+"%")
	}

	// 语言筛选
	if req.Language != "" {
		m = m.Where(cols.Language, req.Language)
	}

	// 分页查询原始实体
	var entities []*entity.AlertPeople
	if err = m.Offset(req.Offset()).Limit(req.Limit()).ScanAndCount(&entities, &out.Total, false); err != nil {
		return
	}

	deptIds := make([]int64, 0)
	for _, item := range entities {
		if !arrayUtil.IsExistsItem(item.DeptId, deptIds) {
			deptIds = append(deptIds, int64(item.DeptId))
		}
	}
	var deptResults []*entity.Dept
	_ = dao.Dept.Ctx(ctx).WhereIn(dao.Dept.Columns().Id, deptIds).Scan(&deptResults)

	// 转换为响应模型
	out.List = make([]*mymodel.AlertPeopleResponse, len(entities))
	for i, e := range entities {
		deptName := ""
		for _, d := range deptResults {
			if d.Id == int(e.DeptId) {
				deptName = d.Name
			}
		}

		out.List[i] = &mymodel.AlertPeopleResponse{
			Id:               e.Id,
			Name:             e.Name,
			DeptId:           e.DeptId,
			Phone:            e.Phone,
			Email:            e.Email,
			Wechat:           e.Wechat,
			Language:         e.Language,
			Remark:           e.Remark,
			ReceiveFrequency: e.ReceiveFrequency,
			CreatedAt:        e.CreatedAt,
			UpdatedAt:        e.UpdatedAt,
			DeptName:         deptName,
		}
	}
	return
}

// UptStatus 更新告警人员状态
func (*sAlertPeople) UptStatus(ctx context.Context, id int, status int) (err error) {
	return
}

// Del 删除告警人员
func (*sAlertPeople) Del(ctx context.Context, id int) (err error) {
	// 这里可以添加删除前的关联检查逻辑
	number, _ := dao.AlertPeopleToScene.Ctx(ctx).Where(dao.AlertPeopleToScene.Columns().PeopleId, id).Count()
	if number > 0 {
		err = errors.New("cannot delete a bound scene person")
		return
	}
	_, err = dao.AlertPeople.Ctx(ctx).WherePri(id).Delete()
	return
}

// GetOne 获取一条告警人员信息
func (*sAlertPeople) GetOne(ctx context.Context, id int) (out *entity.AlertPeople, err error) {
	out = new(entity.AlertPeople)
	err = dao.AlertPeople.Ctx(ctx).WherePri(id).Scan(&out)
	return
}

// GetOptions 获取表单告警人员选项
func (*sAlertPeople) GetOptions(ctx context.Context, in *v1.AlertPeopleGetOptionsReq) (out *v1.AlertPeopleGetOptionsRes, err error) {
	out = new(v1.AlertPeopleGetOptionsRes)
	var data []*entity.AlertPeople
	m := dao.AlertPeople.Ctx(ctx)
	if in.DeptId > 0 {
		m = m.Where(cols.DeptId, in.DeptId)
	}
	superDept, currentUser, _ := service.User().IsCurrentUserSuperDept(ctx)
	if !superDept {
		m = m.Where(cols.DeptId, currentUser.DeptId)
	}
	err = m.Scan(&data)
	if err != nil {
		glog.Line().Error(ctx, err)
		return
	}
	out.Options = make([]*api.FormOptionsItem, 0)
	if data != nil {
		for _, v := range data {
			out.Options = append(out.Options, &api.FormOptionsItem{
				Value: v.Id,
				Label: v.Name + "(" + v.Phone + ")",
			})
		}
	}
	return
}
